const events = require('events');
const request = require('request')
const Lib = require("./lib");
const ws = require("ws");

class Index extends events {
    constructor(roomId) {
        super()
        this.roomId = roomId
        this.emitter = new events.EventEmitter()
        this.ws_info = new Lib(this.roomId)
        this.userInfoApi = 'https://api.bilibili.com/x/space/acc/info?mid='
    }

    start() {
        let {ws_url, login_data} = this.ws_info.get_ws_info()
        this.client = new ws(ws_url)
        this.client.on('open', res => {
            login_data.forEach((item, index) => {
                // console.log(item.toString())
                this.client.send(item)
            })
            setInterval(() => {
                // console.error(this.ws_info.heartbeatInterval, '发送心跳包')
                this.client.send(this.ws_info.heartbeat)
            }, this.ws_info.heartbeatInterval);
        })
        this.client.on('message', data => {
            this.on_message(data)
        })
        this.client.on('close', async () => {

        })
    }

    stop() {
        this.client.close()
    }

    asyncRequest(url) {
        console.log(url)
        return new Promise((resolve, reject) => {
            request(url, (error, response, data) => {
                if (error) {
                    reject('请求错误')
                }
                resolve(JSON.parse(data).data)
            })
        })
    }

    async getHeadImage(uid) {
        let headImage = ''
        try {
            headImage = await this.asyncRequest(this.userInfoApi + uid)
        } catch (e) {
            return ''
        }
        // console.log(headImage)
        const fileName = headImage.face.slice(headImage.face.lastIndexOf('/') + 1)
        // const fileName = ''
        return 'http://127.0.0.1:9501/static/' + fileName
    }

    on_message(data) {
        let result = {}
        data = this.ws_info.decode_msg(data)[0]

        console.log(data, 66)
        try {
            for (const resultKey in data) {
                let item = data[resultKey]
                if (item.cmd == "SEND_GIFT") {
                    result.type = 'gift'
                    result.nikeName = item.data.uname
                    result.giftName = item.data.giftName
                    result.count = item.data.num
                    this.getHeadImage(item.data.uid).then(res => {
                        console.log(76)
                        result.headImage = res
                        this.emit('message', result)
                    })
                    break
                }
                if (item.cmd == 'DANMU_MSG') {
                    let info = item.info
                    let uid = info[2][0]
                    result.type = 'chatMsg'
                    result.content = info[1]
                    result.nikeName = info[2][1]
                    this.getHeadImage(uid).then(res => {
                        result.headImage = res
                        this.emit('message', result)
                    })
                    break;
                }
                if (item.cmd == 'ENTRY_EFFECT') {
                    // console.log(data)
                    let content = item.data.copy_writing
                    let uid = item.data.uid
                    if (content.indexOf('舰长') != -1) {
                        result.type = 'vipJoin'
                    } else {
                        result.type = 'join'
                    }
                    result.headImage = item.data.face
                    result.nikeName = content.slice(content.search('<%') + 2, content.search('%>'))
                    result.content = content
                    this.getHeadImage(uid).then(res => {
                        result.headImage = res
                        this.emit('message', result)
                    })
                    break;
                }
                if (item.cmd == 'INTERACT_WORD') {
                    // console.log(data)
                    let uid = item.data.uid
                    result.type = 'join'
                    result.nikeName = item.data.uname
                    this.getHeadImage(uid).then(res => {
                        result.headImage = res
                        this.emit('message', result)
                    })
                    break;
                }
            }

            data = data[0]
            console.log(data)

            // if (data.cmd == 'SEND_GIFT') {
            //     // console.log(data)
            //
            // }


        } catch (e) {
            return
        }
    }
}

exports = module.exports = Index
